package jsi.test.transactions;

import java.sql.SQLException;
import java.util.Date;

import jsi.domain.Person;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class TxServiceImpl extends HibernateDaoSupport implements TxService {

	public void insertAndThrowChecked() throws Exception {
		final Person person = new Person("Jakub", new Date());
		getHibernateTemplate().save(person);
		throw new Exception("------");
	}

	public void insertAndThrowRuntime() throws RuntimeException {
		final Person person = new Person("Jakub", new Date());
		getHibernateTemplate().save(person);
		throw new RuntimeException("------");
	}

	public long insertSuccessfully() {
		Person person = new Person("Jakub", new Date());
		return (Long) getHibernateTemplate().save(person);
	}

	public int countRows() {
		return (Integer) getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				SQLQuery query = session.createSQLQuery("select count(1) from Person");
				Integer count = (Integer)query.list().get(0);
				return count;
			}
			
		});
	}

}
